<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue"
import { WorkSpace } from "./index"
import { Banner as BannerPreview, ProcessNode as ProcessNodePreview, CertificateContent as CertificateContentPreview, Footer as FooterPreview } from "#/components/certificate-home"

import EmptyImage from "#/assets/images/banner-empty.png"
import { createCertificateFirstPageApi, getCertificateFirstPageApi } from "#/api/certificate/list"
import { ElMessage, ElMessageBox } from "element-plus"
import { cloneDeep } from '@vben/utils';
import { $t } from "#/locales"
import { isValidJSON } from '#/utils/isValidJSON'

defineOptions({ name: 'SetCertificateHomeDialog' })
const emit = defineEmits(['queryTable'])
const dialogVisible = ref(false)
const editData = ref()
const settingLoading = ref(false)
const submitLoading = ref(false)
const defaultWorkSpace = ref<any>({
  banner: {
    bannerUrl: '',
    textConfigs: []
  },
  processNode: {
    processNodeConfigs: []
  },
  certificateContent: {
    certificateContentConfigs: []
  },
  footer: {
    showFooter: false,
    provideContent: '',
    phone: '',
    email: '',
    publicAccount: {
      code: '',
      desc: ''
    },
    service: {
      code: '',
      desc: ''
    }
  },
  activeName: 'banner'
})
const workSpaceData = ref()
const workSpace = ref(cloneDeep(defaultWorkSpace.value))
const previewVisible = ref(false)
const processNodeWidth = ref('100%')

// 子组件引用
const workSpaceRef = ref()

const getCertificateFirstPage = () => {
  settingLoading.value = true
  getCertificateFirstPageApi({
    certificateId: editData.value.id,
    status: 0
  }).then((res: any) => {
    const { configTemplate } = res
    workSpaceData.value = res
    // 解析 configTemplate 并保持 workSpace 的完整结构
    try {
      const parsedConfig = isValidJSON(configTemplate) ? JSON.parse(configTemplate) as any[] : []
      const config = parsedConfig?.[0] || {}
      // 使用 Object.assign 来合并数据，保持默认结构
      workSpace.value = {
        ...cloneDeep(defaultWorkSpace.value),
        ...config
      }
    } catch (error) {
      console.error('解析 configTemplate 失败:', error)
      // 如果解析失败，保持默认结构
    }
  }).finally(() => {
    console.log('getCertificateFirstPage')
    settingLoading.value = false
  })
}

const inint = (data: any = null) => {
  if (data) {
    editData.value = data
    getCertificateFirstPage()
  }
  dialogVisible.value = true
  nextTick(() => {
    processNodeWidth.value = getWidth()
  })
}

const onCancel = () => {
  if (previewVisible.value) {
    previewVisible.value = false
    return
  }
  ElMessageBox.confirm($t('certificate.saveDraft'), $t('common.tipTxt'), {
    confirmButtonText: $t('common.submitTxt'),
    cancelButtonText: $t('common.cancelTxt'),
    type: 'warning',
  }).then(() => {
    onSubmit('DRAFT')
  }).catch(() => {
    dialogVisible.value = false
    workSpace.value = cloneDeep(defaultWorkSpace.value)
    console.log(workSpace.value)
  })
}

const coverData = (data: any) => {
  ElMessageBox.confirm($t('certificate.updateCover'), $t('common.tipTxt'), {
    confirmButtonText: $t('common.submitTxt'),
    cancelButtonText: $t('common.cancelTxt'),
    type: 'warning',
  }).then(() => {
    const params = {
      ...data,
      cover: true
    }
    submitLoading.value = true
    createCertificateFirstPageApi(params).then((res: any) => {
      console.log(res)
      if (!!res) {
        dialogVisible.value = false
        workSpace.value = cloneDeep(defaultWorkSpace.value)
        ElMessage.success($t('certificate.configSuccess'))
        emit('queryTable')
      }
    }).finally(() => {
      submitLoading.value = false
    })
  }).catch(() => {
    dialogVisible.value = false
    workSpace.value = cloneDeep(defaultWorkSpace.value)
    emit('queryTable')
  })
}

const onSubmit = async (type: string) => {
  // 表单校验
  try {
    // 校验所有必填字段
    const isValid = await workSpaceRef.value?.validate()
    console.log('isValid', isValid)
    if (!isValid) {
      ElMessage.error($t('certificate.pleaseCompleteRequiredFields'))
      return
    }

    submitLoading.value = true
    console.log(workSpace.value)
    const params = {
      certificateId: editData.value.id,
      configTemplate: JSON.stringify([workSpace.value]),
      status: type === 'PUBLISH' ? 1 : 0,
      id: workSpaceData.value?.id || null
    }
    createCertificateFirstPageApi(params).then((res: any) => {
      console.log('onSubmit')
      console.log(res)
      if (isValidJSON(res)) {
        res = JSON.parse(res)
      }
      const { code } = res
      if (code === '201') {
        coverData(params)
      } else {
        ElMessage.success($t('certificate.configSuccess'))
        dialogVisible.value = false
        workSpace.value = cloneDeep(defaultWorkSpace.value)
        console.log(workSpace.value)
        emit('queryTable')
      }
    }).finally(() => {
      submitLoading.value = false
    })
  } catch (error) {
    console.error('表单校验失败:', error)
    ElMessage.error($t('certificate.pleaseCompleteRequiredFields'))
  }
}

const onPreview = () => {
  previewVisible.value = true
}

const handleBannerUpdate = (newBanner: any) => {
  workSpace.value.banner = newBanner
}

const getWidth = () => {
  const width = document.body?.clientWidth
  console.log('getWidth', width)
  if (previewVisible.value) {
    return '100%'
  }
  return width ? width - 385 + 'px' : '100%'
}

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    // 更新响应式宽度
    processNodeWidth.value = getWidth()
    console.log('handleResize', processNodeWidth.value)
  })
}

// 监听 previewVisible 变化
watch(previewVisible, () => {
  nextTick(() => {
    // 当预览模式切换时，重新计算宽度
    handleResize()
  })
})

onMounted(() => {
  console.log('onMounted')
  // 添加窗口大小变化监听器
  window.addEventListener('resize', handleResize)
  // 初始化宽度
  nextTick(() => {
    processNodeWidth.value = getWidth()
  })
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize)
})

defineExpose({ inint })

</script>
<template>
  <el-drawer id="mock-template-drawer" :destroy-on-close="true" :close-on-click-modal="false"
    :close-on-press-escape="false" :append-to-body="true" body-class="drawer-canvas-body" :with-header="false"
    class="detail-war" size="100%" v-model="dialogVisible" direction="rtl">
    <template #default>
      <div v-loading="settingLoading" class="flex h-full">
        <div :style="{ display: previewVisible ? 'none' : 'block' }" class="w-[385px] h-full bg-[#fff] custom-shadow">
          <WorkSpace ref="workSpaceRef" v-model:workSpace="workSpace" />
        </div>
        <div class="flex-1 h-full" :style="{ width: previewVisible ? '100%' : processNodeWidth }">
          <div class="w-full h-full overflow-y-scroll">
            <div id="banner" class="w-full h-auto mb-[16px]">
              <BannerPreview v-show="workSpace.banner.bannerUrl" v-model:banner="workSpace.banner"
                @update:banner="handleBannerUpdate" :edit="!previewVisible" />
              <div v-show="!workSpace.banner.bannerUrl" class="flex-center h-500 bg-[#E1E2ED]">
                <el-empty :image-size="200" :image="EmptyImage" class="text-[#595959]"
                  :description="$t('certificate.settingBanner.uploadBanner')" />
              </div>
            </div>
            <div id="processNode" class="w-full m-auto max-w-[1248px] pl-[24px] pr-[24px] mb-[16px]">
              <ProcessNodePreview v-show="workSpace.processNode.processNodeConfigs.length"
                v-model:processNode="workSpace.processNode" />
              <div
                v-show="workSpace.processNode.processNodeConfigs.length === 0 && workSpace.activeName === 'processNode'"
                class="w-full h-auto bg-[#fff] rounded-[16px] pt-[38px] pb-[38px]">
                <div class="w-full h-auto leading-[22px] text-[14px] text-center flex-center text-[#595959]">
                  {{ $t('certificate.settingProcessNode.noContent') }}
                </div>
              </div>
            </div>
            <div id="content" class="w-full max-w-[1248px] m-auto pl-[24px] pr-[24px] mb-[16px]">
              <CertificateContentPreview v-show="workSpace.certificateContent.certificateContentConfigs.length"
                v-model:certificateContent="workSpace.certificateContent" />
              <div
                v-show="workSpace.certificateContent.certificateContentConfigs.length === 0 && workSpace.activeName === 'content'"
                class="w-full h-auto bg-[#fff] rounded-[16px] pt-[38px] pb-[38px]">
                <div class="w-full h-auto leading-[22px] text-[14px] text-center flex-center text-[#595959]">
                  {{ $t('certificate.settingCertificateContent.noContent') }}
                </div>
              </div>
            </div>
            <div id="footer" class="w-full">
              <FooterPreview v-show="workSpace.footer.showFooter" v-model:footer="workSpace.footer" />
            </div>
          </div>
        </div>

      </div>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button v-show="!previewVisible" @click="onPreview">{{ $t('common.previewTxt') }}</el-button>
        <el-button v-show="!previewVisible" type="primary" @click="onSubmit('PUBLISH')" :loading="submitLoading">{{
          $t('common.submitTxt') }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 0px;
}

.hide-upload-btn :deep(.el-upload--picture-card) {
  display: none !important;
}

:deep(.el-form-item--label-top) {
  .el-form-item__label {
    display: block;
    width: 100%;
    padding: 0px;
  }
}

.play-icon {
  cursor: pointer;
  transition: transform 0.2s;
}

.play-icon-active {
  transform: rotate(90deg) scale(0.6);
  transition: transform 0.2s;
}

:deep(.el-form-item--label-top .el-form-item__label) {
  margin-bottom: 0px;
}

:deep(.el-color-picker),
:deep(.el-color-picker__trigger) {
  width: 14px;
  height: 14px;
  line-height: 0px;
  padding: 0px;
  border: none;
  border-radius: 7px;
  overflow: hidden;

  span,
  i,
  svg {
    display: none;
  }
}

.custom-shadow {
  box-shadow: 0px 2px 9px 0px rgba(0, 0, 0, 0.16);
}
</style>
<style lang="scss">
#mock-template-drawer .drawer-canvas-body {
  padding: 0px !important;
  background-color: #EDEEF5 !important;
}
</style>
